package com.project.fiveCerealsSavoury.service.impl;
import java.io.UnsupportedEncodingException;
import java.nio.file.FileSystems;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.project.fiveCerealsSavoury.domain.Address;
import com.project.fiveCerealsSavoury.domain.DeliveryDomain;
import com.project.fiveCerealsSavoury.domain.Goods;
import com.project.fiveCerealsSavoury.domain.Message;
import com.project.fiveCerealsSavoury.domain.Order;
import com.project.fiveCerealsSavoury.domain.OrderState;
import com.project.fiveCerealsSavoury.domain.Trade;
import com.project.fiveCerealsSavoury.domain.TradeStatus;
import com.project.fiveCerealsSavoury.domain.User;
import com.project.fiveCerealsSavoury.exception.BizException;
import com.project.fiveCerealsSavoury.service.AddressService;
import com.project.fiveCerealsSavoury.service.GoodsService;
import com.project.fiveCerealsSavoury.service.IntegrationService;
import com.project.fiveCerealsSavoury.service.OrderService;
import com.project.fiveCerealsSavoury.service.ReportFormsService;
import com.project.fiveCerealsSavoury.service.TradeService;
import com.project.fiveCerealsSavoury.service.UserService;
import com.project.fiveCerealsSavoury.transfer.AddOrder;
import com.project.fiveCerealsSavoury.transfer.Page;
import com.project.fiveCerealsSavoury.transfer.UserBalace;
import com.project.fiveCerealsSavoury.transfer.UserBuy;
import com.project.fiveCerealsSavoury.transfer.UserLogin;
import com.project.fiveCerealsSavoury.transfer.UserPage;
import com.project.fiveCerealsSavoury.transfer.UserRetreat;
import com.project.fiveCerealsSavoury.transfer.UserSet;

@Service
@Transactional
public class IntegrationServiceImpl implements IntegrationService {
	@Autowired
	private UserService userService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private TradeService tradeService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private AddressService addressService;
	@Override
	public boolean reg(User user) throws BizException {
		if(user !=null){
			userService.reg(user);
			return true;
		}
		return false;
		
	}
	@Override
	public User login(UserLogin userLogin) throws BizException {
		if(userLogin == null)throw new BizException("没有此用户");
		return userService.login(userLogin.getName(), userLogin.getPasswd());
	}

	@Override
	public void full(UserBalace userBalace) throws BizException {
		if(userBalace == null)throw new BizException("用户不存在");
		userService.fullMoney(userBalace.getMoney(),userBalace.getUserId());
	}

	@Override
	public void setUser(UserSet userSet) throws BizException {
		if(userSet == null) throw new BizException("用户不存在");
		userService.setUser(userSet.getNewPasswd(),userSet.getNewPhone(),userSet.getUserId());
		
	}

	@Override
	public User queryUser(Integer userId) throws BizException {
		if(userId == null) throw new BizException("用户不存在");
		return userService.query(userId);
	}

	@Override
	public Message bug(UserBuy userBuy, Integer userId)throws BizException {
		// 查询用户
		User user = userService.query(userId);
		// 查询商品
		Goods goods = goodsService.query(userBuy.getGoodId());
		Address query = addressService.queryAddress(userBuy.getAddressId());
		// 送货地址
		List<String> address=Arrays.asList("内蒙古","新疆","广西","西藏","宁夏","台湾");
		if(address.contains(query)){
			// 地区偏远，不便配送
			throw new BizException("地方偏远，不便配送");
		}
		if (userBuy.getGoodNumber()>userBuy.getGoodNumber()) {
			throw new BizException("库存不足");
		}
		String orderNumber = UUID.randomUUID()+"";
		Order order = new Order();
		order.setId(order.getId());
		order.setUserId(user.getId());
		order.setUserName(query.getNickName());
		order.setUserPhone(query.getUserPhone());
		order.setRemark(userBuy.getRemark());
		order.setEndAddress(query.getAddress()+query.getDetailedAddress());
		order.setOrderNumber(orderNumber);
		order.setGoodPrice(userBuy.getGoodPrice());
		order.setOrderTime(new Timestamp(new Date().getTime()));
		order.setGoodName(userBuy.getGoodName());
		order.setGoodNumber(userBuy.getGoodNumber());
		// 判断用户金额是否充足
		if(user.getMoney() < userBuy.getGoodPrice()*userBuy.getGoodNumber()){// 用户余额小于商品现价，余额不足，订单加入未支付
			// 余额不足
			
			order.setOrderState(OrderState.未支付);
			orderService.addOrder(order);
			throw new BizException("余额不足，已加入未支付订单");
		}else{
			Double money2 = user.getMoney();
			// 商品的价格
			Double goodMoney=userBuy.getGoodNumber() * userBuy.getGoodPrice();
			// 用户余额
			Double money = user.getMoney() - goodMoney;
			user.setMoney(money);
			userService.fullMoney(money, user.getId());
			order.setOrderState(OrderState.已支付);
			orderService.addOrder(order);
			// 添加交易记录
			Order orderId = orderService.queryByOrderState(order.getOrderNumber());
			Trade trade=new Trade(money2, money, goodMoney, new Timestamp(new Date().getTime()), user.getName(), user.getId(), TradeStatus.USER, goods.getWeight(),orderId.getId());
			tradeService.tradeAdd(trade);
			trade.setTradeStatus(TradeStatus.INTERIOR);
			tradeService.tradeAdd(trade);
			return new Message(order);
		}
	}

	@Override
	public Message retreat(UserRetreat userRetreat) throws BizException{
		// 查询用户所有的订单
		List<Order> queryStateOrder = orderService.queryStateOrder(userRetreat.getUserId(), OrderState.已支付);
		for (Order order : queryStateOrder) {
			if(order !=null && order.getUserId().equals(userRetreat.getUserId())){
				Order queryById = orderService.queryById(userRetreat.getOrderId(), OrderState.已支付);
				if(queryById == null){
					throw new BizException("还没有订单");
				}else if(queryById.getId().equals(userRetreat.getOrderId())){
//					boolean removeOrder = orderService.removeOrder(queryById.getOrderNumber(), OrderState.已支付);
//					if(removeOrder == true){
						User user = userService.query(userRetreat.getUserId());
						List<Goods> queryAll = goodsService.queryAll(order.getGoodName());
						if(queryAll == null){
							throw new BizException("没有此商品");
						}
						for (Goods goods : queryAll) {
							if(goods !=null && goods.getGoodName().equals(order.getGoodName())){
								Double goodmoney=goods.getNowPrice() * order.getGoodNumber();
								Double userMoney=user.getMoney() + goodmoney;
								orderService.modifyDele(queryById.getOrderNumber(), OrderState.已取消,new Timestamp(new Date().getTime()));
								Trade trade = new Trade(user.getMoney(), userMoney, goodmoney, new Timestamp(new Date().getTime()), user.getName(), user.getId(), TradeStatus.USER, goods.getWeight(),userRetreat.getOrderId());
								tradeService.tradeAdd(trade);
								return new Message(order);
							}
						}
					}else{
						throw new BizException("退单失败");
					}
				}
//			}else{
//				throw new BizException("该用户没有订单");
			}
//		}
		return null;
	}
	
	@Override
	public Page queryTrade(Integer userId,Integer pageIndex) throws BizException{
		UserPage userPage = new UserPage();
		if (pageIndex == null) {
			pageIndex = 1;
		}
		userPage.setPageIndex(pageIndex);
		userPage.setPageSize(15);
		Page listQuery = tradeService.listQuery(userPage, userId);
		if(listQuery == null) throw new BizException("没有订单");
		return listQuery;
	}
	/**
	 * 查询所有管理员
	 */
	@Override
	public List<User> queryAdmin(String isAdmin) throws BizException{
		List<User> ia = userService.queryIsAdmin(isAdmin);
		if(ia != null){
			return ia;
		}
		return null;
	}


	@Override
	public boolean addShop(AddOrder addOrder) throws BizException, UnsupportedEncodingException{

			Order queryById = orderService.queryCar(addOrder.getUserId(),addOrder.getGoodName(), OrderState.已添加到购物车);
			if (queryById == null) {
				orderService.addToCar(addOrder);
			}else{
				orderService.modifyNumber(addOrder.getId(),addOrder.getCount());
			}
		return true;
	}


//	@Override
//	public boolean remove(Integer id) throws BizException{
//
//			boolean remove = userService.remove(id);
//			if(remove){
//				return true;
//			}
//		
//		return false;
//	}

	@Override
	public Order pay(Integer id) throws BizException {
		Order queryById = orderService.queryById(id, OrderState.未支付);
		if(queryById !=null){
			Double money=queryById.getGoodPrice() * queryById.getGoodNumber();
			User query = userService.query(queryById.getUserId());
			if(query.getMoney() < money){
				throw new BizException("余额不足，请充值");
			}else{
				userService.fullMoney(query.getMoney()-money, queryById.getUserId());
				orderService.modifyOrderState(queryById.getOrderNumber(), OrderState.已支付);
				Trade trade = new Trade(query.getMoney(), query.getMoney(), money, new Timestamp(new Date().getTime()), query.getName(), query.getId(), TradeStatus.USER,query.getMoney(),queryById.getId());
				tradeService.tradeAdd(trade);
			}
			return queryById;
		}
		return null;
	}

	@Override
	public boolean setIsgin(Integer id, String isSign) throws BizException {
		boolean remend = userService.remend(id, isSign);
		if(remend){
			return true;
		}
		return false;
	}
}
